﻿using System;

namespace WeiSha.Core.Method.Snowflake
{
	// Token: 0x0200003E RID: 62
	internal class SnowflakeTool
	{
		// Token: 0x06000292 RID: 658 RVA: 0x000118E0 File Offset: 0x0000FAE0
		public SnowflakeTool(long workerId)
		{
			bool flag = workerId > SnowflakeTool.maxWorkerId || workerId < 0L;
			if (flag)
			{
				throw new Exception(string.Format("Snowflake : 节点id 不能大于 {0} 或者 小于 0 ", workerId));
			}
			SnowflakeTool.nodeId = workerId;
		}

		// Token: 0x06000293 RID: 659 RVA: 0x00011930 File Offset: 0x0000FB30
		public long NextID()
		{
			long num3;
			lock (this)
			{
				long num = this.timeGen();
				bool flag2 = this.lastTimestamp == num;
				if (flag2)
				{
					SnowflakeTool.sequence = (SnowflakeTool.sequence + 1L) & SnowflakeTool.sequenceMask;
					bool flag3 = SnowflakeTool.sequence == 0L;
					if (flag3)
					{
						num = this.tillNextMillis(this.lastTimestamp);
					}
				}
				else
				{
					SnowflakeTool.sequence = 0L;
				}
				bool flag4 = num < this.lastTimestamp;
				if (flag4)
				{
					throw new Exception(string.Format("Snowflake : Clock moved backwards.  Refusing to generate id for {0} milliseconds", this.lastTimestamp - num));
				}
				this.lastTimestamp = num;
				long num2 = (num - SnowflakeTool.twepoch << SnowflakeTool.timestampLeftShift) | (SnowflakeTool.nodeId << SnowflakeTool.workerIdShift) | SnowflakeTool.sequence;
				num3 = num2;
			}
			return num3;
		}

		// Token: 0x06000294 RID: 660 RVA: 0x00011A1C File Offset: 0x0000FC1C
		private long tillNextMillis(long lastTimestamp)
		{
			long num;
			for (num = this.timeGen(); num <= lastTimestamp; num = this.timeGen())
			{
			}
			return num;
		}

		// Token: 0x06000295 RID: 661 RVA: 0x00011A4C File Offset: 0x0000FC4C
		private long timeGen()
		{
			return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
		}

		// Token: 0x040000C8 RID: 200
		private static long nodeId;

		// Token: 0x040000C9 RID: 201
		private static long twepoch = 687888001020L;

		// Token: 0x040000CA RID: 202
		private static long sequence = 0L;

		// Token: 0x040000CB RID: 203
		private static int workerIdBits = 5;

		// Token: 0x040000CC RID: 204
		public static long maxWorkerId = -1L ^ (-1L << SnowflakeTool.workerIdBits);

		// Token: 0x040000CD RID: 205
		private static int sequenceBits = 12;

		// Token: 0x040000CE RID: 206
		private static int workerIdShift = SnowflakeTool.sequenceBits;

		// Token: 0x040000CF RID: 207
		private static int timestampLeftShift = SnowflakeTool.sequenceBits + SnowflakeTool.workerIdBits;

		// Token: 0x040000D0 RID: 208
		public static long sequenceMask = -1L ^ (-1L << SnowflakeTool.sequenceBits);

		// Token: 0x040000D1 RID: 209
		private long lastTimestamp = -1L;
	}
}
